package com.xtaller.sdboot.utils.helper;

import com.xtaller.sdboot.utils.bean.JwtModel;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import io.jsonwebtoken.*;
import lombok.var;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.HashMap;

/**
 * @author : Taller
 * @date : 2020/2/7 08:03
 * @Description : Jwt工具
 */
public class JwtHelper {
    /**
     * Token过期
     * */
    public static final int JWT_ERRCODE_EXPIRE = 4001;
    /**
     * 验证不通过
     * */
    public static final int JWT_ERRCODE_FAIL = 4002;
    /**
     * 密匙
     * */
    public static final String JWT_SECRET = "8677df7fc3a99e26a61c114d5ec8245d";



    /**
     * 签发JWT
     * @param id
     * @param info   认证数据
     * @param ttlMillis
     * @return  String
     */
    public static String createJWT(String id, HashMap<String, Object> info, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                // 主题
                .setSubject(JsonHelper.o2s(info))
                // 签发者
                .setIssuer("jt-cloud")
                // 签发时间
                .setIssuedAt(now)
                // 签名算法以及密匙
                .signWith(signatureAlgorithm, secretKey);
        if (ttlMillis > 0) {
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            // 过期时间
            builder.setExpiration(expDate);
        }
        return builder.compact();
    }


    /**
     * 验证JWT
     * @param jwtStr
     * @return
     */
    public static JwtModel validateJWT(String jwtStr) {
        var jwt = new JwtModel();
        Claims claims = null;
        try {
            claims = parseJWT(jwtStr);
            jwt.setSuccess(true);
            jwt.setClaims(claims);
            jwt.setUserId(claims.getId());
        } catch (ExpiredJwtException e) {
            jwt.setErrCode(JWT_ERRCODE_EXPIRE);
            jwt.setSuccess(false);
            jwt.setMessage("Token已经过期");
        } catch (SignatureException e) {
            jwt.setErrCode(JWT_ERRCODE_FAIL);
            jwt.setSuccess(false);
            jwt.setMessage("Token已经过期");
        } catch (Exception e) {
            jwt.setErrCode(JWT_ERRCODE_FAIL);
            jwt.setSuccess(false);
            jwt.setMessage("Token认证失败");
        }
        return jwt;
    }

    public static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JWT_SECRET);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     *
     * 解析JWT字符串
     * @param jwt
     * @return
     * @throws Exception
     */
    private static Claims parseJWT(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
